package com.though.weixin.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PayConfg {

	private static final Logger logger = LoggerFactory.getLogger(PayConfg.class);
	
	private static final String CONFIG = "/pay-config.properties";

	private static final String CONFIG_TEMPLATE = "/pay-config-template.properties";
	
	private volatile PayConfigParams payConfigParams;
	
	public PayConfg() {
		init();
	}
	
	public void init() {
		InputStream in = PayConfg.class.getResourceAsStream(CONFIG);
		if (in == null) {
		    in = PayConfg.class.getResourceAsStream(CONFIG_TEMPLATE);
		    if (in == null)
		        throw new RuntimeException("pay-config.properties is not config");
        }
		this.payConfigParams = loadConfgParams(in);
	}

	private PayConfigParams loadConfgParams(InputStream in) {
		Properties properties = new Properties();
		try {
			properties.load(in);
			
			String appid = properties.getProperty("weixin.appid");
			String mch_id = properties.getProperty("weixin.mch_id");
			String sign_key = properties.getProperty("weixin.sign_key");
			String apiclient_cert = properties.getProperty("weixin.apiclient_cert");
			
			PayConfigParams params = new PayConfigParams(appid, mch_id, sign_key, apiclient_cert);
			return params;
			
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					logger.error("Error:close oss propertis file", e);
				}
			}
		}
	}

	public PayConfigParams getConfigParams() {
		return payConfigParams;
	}
}
